#include "../source/server.hpp"
uint64_t connid = 0;
std::unordered_map<int,PtrConnection> _conns;
EventLoop base_loop;
LoopThreadPool* pool;
void OnConnect(const PtrConnection& conn)
{
    DLOG("ONConnect %p",conn.get());
}

void MsgConnect(const PtrConnection& conn,Buffer* buffer)
{
    //接收信息，然后转发
    DLOG("%s",buffer->ReadPosition());
    buffer->MoveReadOffSet(buffer->ReadAbleSize());
    std::string str = "echo hello!";
    conn->Send(str.c_str(),str.size());
}   
void ConnectionDestroy(const PtrConnection& conn)
{
    DLOG("ConnectDestroy %p",conn.get());
    _conns.erase(conn->Id());
}

void NewConnection(int newfd)
{
    ++connid;
    PtrConnection conn(new Connection(connid,newfd,pool->NextLoop()));
    conn->SetConnectCallback(std::bind(OnConnect,std::placeholders::_1));
    conn->SetMessageCallback(std::bind(MsgConnect,std::placeholders::_1,std::placeholders::_2));
    conn->SetSvrCallback(std::bind(ConnectionDestroy,std::placeholders::_1));
    conn->SetActiveRelease(10);
    conn->Established();
    _conns.insert(std::make_pair(connid,conn));
    DLOG("MAIN THREAD");
}

int main()
{
    pool = new LoopThreadPool(&base_loop);
    pool->SetThreadCount(2);
    pool->Create();
    Acceptor acceptor(&base_loop,8083);
    acceptor.SetAcceptCallback(std::bind(NewConnection,std::placeholders::_1));
    acceptor.Listen();
    base_loop.Start();
    return 0;
}